<?php

require_once 'KgridList.php';

//$this->_KgridListing =  new KgridList();
$KgridListing =  new KgridList();




$strAction = $_REQUEST["action"];           //get action from another web page

$strPK_ID = $_REQUEST["num"]; 

$intRowIDGet = $_REQUEST["rowid"]; 
$intPageIDGet = $_REQUEST["pageid"];  
$intSkipGet = $_REQUEST["skip"];  
$intTotRecordCountGet = $_REQUEST["totcount"];  

//get Sorted by field and PageSize, that are passed as well
$strSortField = $_REQUEST["sortby"];  
$strPageSizeGet = $_REQUEST["pagesize"];  

  if ($strPageSizeGet == ""
            || strlen($strPageSizeGet) == 0)
 {
                  $intPageSizeGet = 1;     //so as not to divide by 0
 }
 else
 {
                  $intPageSizeGet = $strPageSizeGet;
 }


 

// Check to see if field changed is one sorted on
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
 $strmachchanged = $_REQUEST["machchanged"];  //always will be a value (0 or 1)
 $strarraychanged = $_REQUEST["arraychanged"];  
 $strstartdatechanged = $_REQUEST["sdatechanged"];  

//now workout if run SkipCount (ie sort field changed)
$len = strlen($strSortField);
$intf = strpos($strSortField, " ");
if ($intf > 1)
{
 $strSortBy = substr($strSortField,0,$intf);
}
//echo $strSortBy;
$strDoSkip = "False";

if ($strmachchanged == 1)   //changed
{
  if ($strSortBy == "Loaded_Machine")  
  {
    $strDoSkip = "True";
  }
}

if ($strarraychanged == 1)   //changed
{
  if ($strSortBy == "Array_Name")  
  {
    $strDoSkip = "True";
  }
}

if ($strstartdatechanged == 1)   //changed
{
  if ($strSortBy == "Start_Date")  
  {
    $strDoSkip = "True";
  }
}
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&



//echo $intTotRecordCountGet;
//Check Total Record Count and decide whether to do skipcount, when sort field changed
$strchgsortfieldbigtot = "False";
if ($intTotRecordCountGet < 40000)
{
  //check if sort field changed
  if ($strDoSkip == "True")
  {
    //do skipcount
    $strDoSkip = "True";
  }
  else
  {
    //do not do skipcount
    $strDoSkip = "False";
  }
   
}
else
{
  //check if sort field changed and OVER 40000 total records. If not on sort field then juat go back to record
  if ($strDoSkip == "True")
  {
        //go to 1st record, do not do skipcount
        $strDoSkip = "False";
        $intRowIDGet = 0;
        $intPageIDGet = 1;
        $intSkipGet = 0;
        $strchgsortfieldbigtot = "True";
        $strErrMsg = "Error - Record has been Updated, but as changing a Sorted field, will cause too much time, Please close and Edit again to see changes!";
        //echo $strDoSkip;
  }


}

//echo $strDoSkip;



//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
 //Please change fields to be updated
 //------------------------------------------
                $strmachtosave = $_REQUEST["machtosave"];   
                $strarraytosave = $_REQUEST["arraytosave"];  
                
 

if (isset($_REQUEST["startdatetosave"]))
{
	$strstartdatetosave = $_REQUEST["startdatetosave"];
                //$strstartdatetosave = urldecode($strstartdatetosave);
}
	else
{
    $strstartdatetosave = "";
}


if (isset($_REQUEST["enddatetosave"]))
{
	$strenddatetosave = $_REQUEST["enddatetosave"];
}
	else
{
    $strenddatetosave = "";
}


if (isset($_REQUEST['notetosave']))
{
	$strnotetosave = $_REQUEST['notetosave'];
}
else
{
    $strnotetosave = "";
}


if (isset($_REQUEST["chktosave"]))
{
	$blnchktosave = $_REQUEST["chktosave"];
}
else
{
    $blnchktosave = "";
}

//END Fields to be Updated
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&



//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
//Next Sort and Search fields are for if using LIST in conjunction (Do not need for Standalone Update form)
//----------------------------------------------------------------------------------------------------------
                $strarraysearch = $_REQUEST["arraysearch"];  
                //$strmachsearch = $_REQUEST["machsearch"]; 
                $strmachsearch = "";
             
//END Optional Fields               
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&




              UpdateDBase($strSortField, $strPageSizeGet, $strPK_ID, $strarraytosave, $strmachtosave, $blnchktosave, $strnotetosave, $strstartdatetosave, $strenddatetosave, $strDoSkip, $strarraysearch, $strmachsearch);


               $strReinitialise = " False ";


                if ($blPageValid == "false"
                   || $strchgsortfieldbigtot == "True")
                {
                     //Response.Write(strErrMsg);
                     echo $strErrMsg;
                     //Response.End();
                }
                else
                {
                  if ($strAction == "byitself")           //DO not refresh LIST (if used)
                  {
                      //Response.Write(" ");      //pass back nothing
                      echo " ";
                      //Response.End();
                  }
                  else
                  { 

                    //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
                    //the next line is used also to check if Sort and Search Criteria fields have been changed (ie strReinitialise parameter)
                    //The next part is for using LIST in conjunction (Do not need for Standalone Update form)

                    if ($runSkipCount == "True")
                    {
                      $intRowIDGet = $intRowIDGetGlobal;
                      $intPageIDGet = $intPageIDGetGlobal;
                      $intSkipGet = $intSkipGetGlobal;
                      //$strarraysearch = "";          //set search criteria as blank
                      //$strReinitialise = " True ";   //set search criteria as blank
                    }


                     //echo $runSkipCount;
                     //echo $strPageSizeGet;


                     $ActionPage = "GetCurrentPage";


                     $KgridListing->ajaxkgridlist($ActionPage, $strarraysearch, $strmachsearch, $intPageIDGet, $strSortField, $intSkipGet, $intRowIDGet, $strPK_ID, $strReinitialise);


                  }       //strAction = "byitself"

                }         //$blPageValid == "false"




    function GetSkipCount($strSortField, $strPageSizeGet, $strPK_ID, $strarraysearch, $strmachsearch)
    {
    //--------------------------------------------------------------------------------------------------------------------
    // PURPOSE SUMMARY:- Re-calculate PageID, RowID and SkipCount (if search or sort fields changed)
    //                                       So as to display in List correctly.
    //
    // PSEUDO CODE:-  Select PK_ID from Array table using unique Sortedby key
    //                              Read all records until PK_ID of record on page matches
    //                               when match found exit out read immediately
    //                               Re-calculate PageID, RowID and SkipCount, using derived RecordCount & PageSize
    //---------------------------------------------------------------------------------------------------------------------

        global $runSkipCount;
        $intwherecounter = 0;
        $intCounter = 0;
        //SqlCommand objCmd;
        $strSQL = "";
         
        $dsn2="SQLSERVER2005";
        $username2="sa";
        $password2="and";
    
        $sqlconnect2=odbc_connect($dsn2,$username2,$password2);

         //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
         //Change as required
         $strSQL = "SELECT PK_ID FROM ARRAYS2 ";                             //customise to your Table
         //$strSQL = $strSQL . " ORDER BY " . $strSortField;                    //customise to your Table
         //$strSQL = $strSQL . " ORDER BY PK_ID";                             //customise to your Table


           $intwherecounter = 0;
        if ($strarraysearch == ""
                    || (strlen($strarraysearch) == 0))
        {
            // nothing to Search
        }
        else
        {
            // NOTE:- To make faster, put % only at end
            $strSQL = $strSQL . " WHERE Array_Name like '%"
                        . $strarraysearch . "%'";
            $intwherecounter = 1;
        }

        if ($strmachsearch == ""
                    || (strlen($strmachsearch) == 0))
        {
            // nothing to Search
        }
        else if (($intwherecounter == 1))
        {
            $strSQL = ($strSQL . (" AND ~dropdownsearch~ = '"
                        . ($strmachsearch . "'")));
        }
        else
        {
            $strSQL = $strSQL . " WHERE ~dropdownsearch~ = '"
                        . $strmachsearch . "'";
        }


        $strSQL = $strSQL . " ORDER BY " . $strSortField;                    //customise to your Table

         //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

        //echo $strSQL;

        $rs=odbc_exec($sqlconnect2, $strSQL);


        //if (!$rs)
        // {
        //    echo "error in Connecting to do Count";
        // }

         $intRecordCount = 0;
         $strnotfound = "Yes";

         while (odbc_fetch_row($rs))
         {

            $intRecordCount = $intRecordCount + 1;

           if (odbc_result($rs,"PK_ID") == $strPK_ID)
           {
              $strnotfound = "No";
              break;
           }
 
          
         }

        odbc_close($sqlconnect2);

        global $intRowIDGetGlobal;
        $intRowIDGetGlobal = 0;
        global $intPageIDGetGlobal;
        $intPageIDGetGlobal = 0;
        global $intSkipGetGlobal;
        $intSkipGetGlobal = 0;

        $intresult = $intRecordCount / $strPageSizeGet;
        $intresult = Floor($intresult);
        $intremainder = $intRecordCount % $strPageSizeGet;

        

        if ($intremainder == 0) 
        {
          $intRowIDGetGlobal = ($strPageSizeGet - 1);                                 //must always take 1 off pageid (ie because row 1 is now row 0, for AJAX grid list)
          if ($intRowIDGetGlobal < 0)                                //check tha rowid is not < 0
          {
            $intRowIDGetGlobal = 0;
          }
          $intPageIDGetGlobal = $intresult;
          $intSkipGetGlobal = ($intresult * $strPageSizeGet) - $strPageSizeGet;
        }

        if ($intremainder > 0) 
        {
          $intRowIDGetGlobal = ($intremainder - 1);                                      //must always take 1 off pageid (ie because row 1 is now row 0, for AJAX grid list)
          if ($intRowIDGetGlobal < 0)                              //check tha rowid is not < 0
          {
            $intRowIDGetGlobal = 0;
          }
          $intPageIDGetGlobal = $intresult + 1;
          $intSkipGetGlobal = (($intresult + 1) * $strPageSizeGet) - $strPageSizeGet;
        }


        $runSkipCount = "True";

         //echo $intCounter;

        //return $intCounter;

    }



    function GetSkipCountNothing($strSortField, $strPageSizeGet, $strPK_ID)
    {
    
        global $runSkipCount;
        $runSkipCount = "False";
    
    }





    function UpdateDBase($strSortField, $strPageSizeGet, $strPK_ID, $strarraytosave, $strmachtosave, $blnchktosave, $strnotetosave, $strstartdatetosave, $strenddatetosave, $strDoSkip, $strarraysearch, $strmachsearch)
    {

       global $strErrMsg;
       global $blPageValid; 
       $blPageValid = "true";
       

        if ($strmachtosave == ""
                    || (strlen($strmachtosave) == 0))
        {
            $strErrMsg = "Error - Machine is required!";
            $blPageValid = "false";
        }


        if ($strarraytosave == ""
                    || (strlen($strarraytosave) == 0))
        {
            $strErrMsg = "Error - Array is required!";
            $blPageValid = "false";
        }

 
        if ($strstartdatetosave == ""
                    || (strlen($strstartdatetosave) == 0))
        {
			 $strStartDate = "NULL";
             //OK
		}
        else
        {
              //$dt="28/02/2007";
		      $dt = $strstartdatetosave;
              $arr=split("/",$dt); // splitting the array
              $dd=$arr[0]; // first element of the array is month
              $mm=$arr[1]; // second element is date
              $yy=$arr[2]; // third element is year
              If(!checkdate($mm,$dd,$yy))
		      {
               $strErrMsg = "Error - Invalid Start Date!";
               $blPageValid = "false";
			  }
              else
			  {
                 $strStartDate = $strstartdatetosave;
			  }
        }

      
        if ($strenddatetosave == ""
                    || (strlen($strenddatetosave) == 0))
        {
			 $strEndDate = "NULL";		 
             //OK
		}
        else
        {
              //$dt="28/02/2007";
		      $dt = $strenddatetosave;
              $arr=split("/",$dt); // splitting the array
              $dd=$arr[0]; // first element of the array is month
              $mm=$arr[1]; // second element is date
              $yy=$arr[2]; // third element is year
              If(!checkdate($mm,$dd,$yy))
		      {
               $strErrMsg = "Error - Invalid End Date!";
               $blPageValid = "false";
			  }
			  else
			  {
                 $strEndDate = $strenddatetosave;
			  }
        }



      if ($blPageValid == "true")
      {


          if ($strStartDate == "NULL")
          {
                //nothing
          }
          else
          {
                $dt = $strStartDate;
                $arr=split("/",$dt); // splitting the array
                $strstartday=$arr[0]; // first element of the array is month
                $strstartmonth=$arr[1]; // second element is date
                $strstartyear=$arr[2]; // third element is year
			    //$strstartyear = substr($strStartDate,0,4);
                //$strstartmonth = substr($strStartDate,5,2);
                //$strstartday = substr($strStartDate,8,2);
                $my_date = gmmktime(0,0,0,$strstartmonth,$strstartday,$strstartyear );
                $strStartDate = date("Ymd",$my_date);
                //ws_conv_date = DateTime.Parse(strstartdatetosave);
                //strStartDate = DateConvitfromformUS(ws_conv_date);        //yyyymmdd isodate format  
                $strStartDate = "'" . $strStartDate . "'";
          }


          if ($strEndDate == "NULL")
          {
                //nothing
          }
          else
          {
			    $dt = $strEndDate;
                $arr=split("/",$dt); // splitting the array
                $strstartday=$arr[0]; // first element of the array is month
                $strstartmonth=$arr[1]; // second element is date
                $strstartyear=$arr[2]; // third element is year
			    //$strstartyear = substr($strEndDate,0,4);
                //$strstartmonth = substr($strEndDate,5,2);
                //$strstartday = substr($strEndDate,8,2);
                $my_date = gmmktime(0,0,0,$strstartmonth,$strstartday,$strstartyear );
                $strEndDate = date("Ymd",$my_date);
                $strEndDate = "'" . $strEndDate . "'";
          }


          //$strarraytosave = $strarraytosave.Replace("'", "''");    //so as to cope with any Apostrophes in text
          //$strnotetosave = $strnotetosave.Replace("'", "''");                             //so as to cope with any Apostrophes in text
          $strarraytosave = str_replace("'","''", $strarraytosave);
          $strnotetosave = str_replace("'","''", $strnotetosave);


          if ($blnchktosave == "true")
          {
                $blnCheck1 = "True";
          }
          else
          {
                $blnCheck1 = "False";
          }



        $dsn2="SQLSERVER2005";
        $username2="sa";
        $password2="and";
     
        $odbc = odbc_connect($dsn2,$username2,$password2);

        //$odbc = odbc_connect ('InterestDB', '', '') or die('Could Not Connect to ODBC Database!');

        //$update = "UPDATE ARRAYS2 SET Array_Name=$bal_new, Interest=$c_interest, Last_Update='$modified' WHERE ID=$userID";

        $update = "UPDATE ARRAYS2 SET Array_Name ='" . $strarraytosave . "',  ";
        $update = $update . "Loaded_Machine ='" . $strmachtosave . "', ";
        $update = $update . "start_date =" . $strStartDate . ", ";
        $update = $update . "end_date =" . $strEndDate . ", ";
        $update = $update . "COMPLETE_FLAG ='" . $blnCheck1 . "', ";
        $update = $update . "comment ='" . $strnotetosave . "' ";
        $update = $update . "WHERE PK_ID = " . $strPK_ID . "";

        //echo $update;
		
        odbc_exec($odbc,$update);

        odbc_close($odbc);



        if ($strDoSkip == "True")
        {
          //$strErrMsg = "Error - Record has been Updated, but as changing a Sorted field, will cause too much time, Please close and Edit again to see changes!";
          //$blPageValid = "false";
          //do not do next line anymore, because the GetSkipCount would take too long with this Sort
          GetSkipCount($strSortField, $strPageSizeGet, $strPK_ID, $strarraysearch, $strmachsearch);

          //GetSkipCountNothing($strSortField, $strPageSizeGet, $strPK_ID);
        }
        else
        {
          GetSkipCountNothing($strSortField, $strPageSizeGet, $strPK_ID);
        }
        
      

      }        //$blPageValid = true

   }







?>
